package com.banzhi.shop.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.R;
import com.banzhi.shop.adapter.CommonAdapter;
import com.banzhi.shop.adapter.CommonHeadAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.Myshouhou.OrderInfo_Data;
import com.banzhi.shop.entity.Myshouhou.Shouhou_Data;
import com.banzhi.shop.model.CallBack.CancelShouhouOrderCallBack;
import com.banzhi.shop.model.CallBack.MyShouhouCallBack;
import com.banzhi.shop.model.ICancelShouhouOrderModel;
import com.banzhi.shop.model.IMyShouhouModel;
import com.banzhi.shop.model.Impl.CancelShouhouOrderImpl;
import com.banzhi.shop.model.Impl.MyShouhouImpl;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.EndlessRecyclerOnScrollListener;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.NumberUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.banzhi.shop.utils.LoadingDialogUtils.showProgress;
import static com.mob.MobSDK.getContext;

/**
 * 我的售后
 */
public class MyShouhouActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener, MyShouhouCallBack, CancelShouhouOrderCallBack {
    private ImageView ivback;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private CommonHeadAdapter<Shouhou_Data> adapter;
    private RelativeLayout rlnodata;
    private IMyShouhouModel model;
    private int page = 1;
    private List<Shouhou_Data> shouhou_datas = new ArrayList<>();
    private ICancelShouhouOrderModel cancelShouhouOrderModel;
    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_shouhou);
        Translucent.setTranslucent(this);
        setinits();
        setListeners();
        model = new MyShouhouImpl();
        cancelShouhouOrderModel = new CancelShouhouOrderImpl();
    }

    @Override
    protected void onStart() {
        super.onStart();
        showProgress(this, "正在加载,请稍后~");
        model.getData(page, this);
    }

    private void setinits() {
        ivback = (ImageView) findViewById(R.id.iv_back);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.srl_listview);
        swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        swipeRefreshLayout.setColorSchemeResources(R.color.themeColor);
        swipeRefreshLayout.setOnRefreshListener(this);
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(layoutManager);
        rlnodata = (RelativeLayout) findViewById(R.id.rl_nodata);
    }

    private void setListeners() {
        ivback.setOnClickListener(this);
        recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                page++;
                showProgress(MyShouhouActivity.this, "正在加载,请稍后~");
                model.getData(page, MyShouhouActivity.this);
            }
        });
    }

    @Override
    public void onRefresh() {
        page = 1;
        showProgress(this, "正在加载,请稍后~");
        model.getData(page, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    /**
     * 获取售后列表成功
     *
     * @param object
     */
    @Override
    public void ongetDataSuccess(Object object) {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        List<Shouhou_Data> datas = (List<Shouhou_Data>) object;
        if (page == 1) {
            shouhou_datas.clear();
        } else {
            if (datas.size() == 0) {
                return;
            }
        }
        shouhou_datas.addAll(datas);
        if (shouhou_datas.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        setViews();
    }

    private void setViews() {
        if (adapter == null) {
            adapter = new CommonHeadAdapter<Shouhou_Data>(this, R.layout.item_shouhou, shouhou_datas) {
                @Override
                public void convert(ViewHolder holder, final Shouhou_Data data, final int position) {
                    holder.setText(R.id.tv_ordernum, data.getRefundno());
                    if ("-2".equals(data.getRefundStatus())) {
                        holder.setText(R.id.tv_statu, "已取消");
                        holder.getTextView(R.id.tv_delete).setVisibility(View.GONE);
                    } else if ("-1".equals(data.getRefundStatus())) {
                        holder.setText(R.id.tv_statu, "已拒绝");
                        holder.getTextView(R.id.tv_delete).setVisibility(View.GONE);
                    } else if ("0".equals(data.getRefundStatus())) {
                        holder.setText(R.id.tv_statu, "申请中");
                        holder.getTextView(R.id.tv_delete).setVisibility(View.VISIBLE);
                    } else if ("1".equals(data.getRefundStatus())) {
                        holder.setText(R.id.tv_statu, "已完成");
                        holder.getTextView(R.id.tv_delete).setVisibility(View.GONE);
                    } else if ("3".equals(data.getRefundStatus())) {
                        holder.setText(R.id.tv_statu, "处理中");
                        holder.getTextView(R.id.tv_delete).setVisibility(View.VISIBLE);
                    } else if ("4".equals(data.getRefundStatus())) {
                        holder.setText(R.id.tv_statu, "处理中");
                        holder.getTextView(R.id.tv_delete).setVisibility(View.GONE);
                    } else if ("5".equals(data.getRefundStatus())) {
                        holder.setText(R.id.tv_statu, "处理中");
                        holder.getTextView(R.id.tv_delete).setVisibility(View.GONE);
                    }

                    if (ASUtils.isCanUse(data.getApplyprice())) {
                        holder.setText(R.id.tv_zongjia, NumberUtils.DecimalFormat(data.getApplyprice()));
                    }
                    holder.getTextView(R.id.tv_xiangqing).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(MyShouhouActivity.this, ShouhouOrderInfoActivity.class);
                            intent.putExtra("id", data.getId());
                            startActivity(intent);
                        }
                    });
                    holder.getTextView(R.id.tv_delete).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            showPopupwindow(data.getId(), position);

                        }
                    });
                    LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
                    layoutManager.setSmoothScrollbarEnabled(true);
                    layoutManager.setAutoMeasureEnabled(true);
                    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                    ((RecyclerView) (holder.getView(R.id.recyclerview))).setLayoutManager(layoutManager);
                    ((RecyclerView) (holder.getView(R.id.recyclerview))).setHasFixedSize(true);
                    ((RecyclerView) (holder.getView(R.id.recyclerview))).setNestedScrollingEnabled(false);
                    CommonAdapter<OrderInfo_Data> adapter = new CommonAdapter<OrderInfo_Data>(MyShouhouActivity.this, R.layout.item_shouhou_item_order, data.getOrderInfo()) {
                        @Override
                        public void convert(ViewHolder holder, OrderInfo_Data orderInfodata, int position) {
                            holder.setImageURI(R.id.iv_image, orderInfodata.getThumb());
                            holder.setText(R.id.tv_title, orderInfodata.getTitle());
                            if (orderInfodata.getOptionname() != null && !"".equals(orderInfodata.getOptionname())) {
                                holder.getTextView(R.id.tv_text_guige).setVisibility(View.VISIBLE);
                                holder.setText(R.id.tv_guige, orderInfodata.getOptionname());
                            } else {
                                holder.getTextView(R.id.tv_text_guige).setVisibility(View.GONE);
                            }
                            if (ASUtils.isCanUse(orderInfodata.getPrice())) {
                                holder.setText(R.id.tv_danjia, NumberUtils.DecimalFormat(orderInfodata.getPrice()));
                            }
                            holder.setText(R.id.tv_num, orderInfodata.getTotal());
                        }
                    };
                    ((RecyclerView) (holder.getView(R.id.recyclerview))).setAdapter(adapter);
                    adapter.setOnItemClickListener(new CommonAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            if ("1".equals(data.getOrderInfo().get(position).getIsregistergoods())) {
                                ToastUtils.makeToastShort("该商品为注册商品");
                            } else if ("0".equals(data.getOrderInfo().get(position).getStatus())) {
                                ToastUtils.makeToastShort("该商品已下架");
                            } else if ("1".equals(data.getOrderInfo().get(position).getDeleted())) {
                                ToastUtils.makeToastShort("该商品已删除");
                            } else {
                                Intent intent = null;
                                if ("1".equals(data.getOrderInfo().get(position).getIsagentgoods())) {
                                     intent = new Intent(MyShouhouActivity.this, CommodityDetails_DZZQActivity.class);
                                } else {
                                     intent = new Intent(MyShouhouActivity.this, CommodityDetailsActivity.class);
                                }
                                intent.putExtra("id", data.getOrderInfo().get(position).getGoodsid());
                                startActivity(intent);
                            }
                        }
                    });
                }

                @Override
                public void headconvert(HeaderViewHolder holder) {

                }
            };
            recyclerView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取售后列表失败
     *
     * @param object
     */
    @Override
    public void ongetDataError(Object object) {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }


    @Override
    public void CancelOrderSuccess(Object object) {
        shouhou_datas.get(position).setRefundStatus("-2");
        adapter.notifyItemChanged(position);
        ToastUtils.makeToastShort("取消售后申请成功");
    }

    @Override
    public void CancelOrderError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }


    /**
     * 点击取消订单
     *
     * @param id
     * @param position
     */
    private void showPopupwindow(final String id, final int position) {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_cancel_shouhou, null);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        final PopupWindow popWindow = new PopupWindow(contentView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        TextView tvcancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        TextView tvtrue = (TextView) contentView.findViewById(R.id.tv_true);
        RelativeLayout rl = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        tvcancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        tvtrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoadingDialogUtils.showProgress(MyShouhouActivity.this, "正在加载,请稍后~");
                cancelShouhouOrderModel.CancelOrder(id, MyShouhouActivity.this);
                MyShouhouActivity.this.position = position;
                popWindow.dismiss();
            }
        });
        popWindow.showAtLocation(contentView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }
}
